package com.mac.intellect_flow.admin.controller.system;

import com.mac.intellect_flow.framework.dto.SysRoleDto;
import com.mac.intellect_flow.framework.dto.SysUserDto;
import com.mac.intellect_flow.framework.model.LoginUser;
import com.mac.intellect_flow.framework.service.CurPermissionService;
import com.mac.intellect_flow.framework.util.JwtUtil;
import com.mac.intellect_flow.framework.util.SecurityUtils;
import com.mac.intellect_flow.reply.PageParam;
import com.mac.intellect_flow.reply.PageResult;
import com.mac.intellect_flow.reply.R;
import com.mac.intellect_flow.sys.entity.SysDept;
import com.mac.intellect_flow.sys.entity.SysRole;
import com.mac.intellect_flow.sys.entity.SysUser;
import com.mac.intellect_flow.sys.entity.SysUserRole;
import com.mac.intellect_flow.sys.service.SysDeptService;
import com.mac.intellect_flow.sys.service.SysMenuService;
import com.mac.intellect_flow.sys.service.SysRoleService;
import com.mac.intellect_flow.sys.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 角色管理
 * 
 * @author mac
 */
@Tag(name = "角色管理")
@RestController
@RequestMapping("/system/role")
public class SysRoleController  {
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private CurPermissionService permissionService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysDeptService deptService;


    @Operation(summary = "角色分页列表")
    @PreAuthorize("@ps.hasPermi('system:role:list')")
    @GetMapping("/list")
    public R<PageResult<SysRole>> list(SysRole role, PageParam pageParam) {
        return R.success(roleService.queryPage(role, pageParam));
    }

  /*  @PreAuthorize("@ps.hasPermi('system:role:export')")
    @PostMapping("/export") {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(response, list, "角色数据");
    }*/

    /**
     * 根据角色编号获取详细信息
     */
    @Operation(summary = "根据角色编号获取详细信息")
    @PreAuthorize("@ps.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public R getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return R.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @Operation(summary = "新增角色")
    @PreAuthorize("@ps.hasPermi('system:role:add')")
    @PostMapping
    public R add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return R.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return R.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        return R.success(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @Operation(summary = "修改保存角色")
    @PreAuthorize("@ps.hasPermi('system:role:edit')")
    @PutMapping
    public R edit(@Validated @RequestBody SysRole role, HttpServletRequest request) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role)) {
            return R.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return R.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (Objects.nonNull(loginUser) && SysUser.isAdmin(SecurityUtils.getUserId())) {
                SysUserDto sysUserDto = userService.selectUserByUserName(loginUser.getUsername());
                loginUser.setRoles(permissionService.getRolePermission(sysUserDto));
                loginUser.setPermissions(permissionService.getMenuPermission(sysUserDto));
                JwtUtil.setRedisUserInfo(request, null,loginUser,true);
            }
            return R.success();
        }
        return R.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @Operation(summary = "修改保存数据权限")
    @PreAuthorize("@ps.hasPermi('system:role:edit')")
    @PutMapping("/dataScope")
    public R dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return R.success(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @Operation(summary = "状态修改")
    @PreAuthorize("@ps.hasPermi('system:role:edit')")
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return R.success(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @Operation(summary = "状态修改")
    @PreAuthorize("@ps.hasPermi('system:role:remove')")
    @DeleteMapping("/{roleIds}")
    public R remove(@PathVariable Long[] roleIds) {
        return R.success(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @Operation(summary = "获取角色选择框列表")
    @PreAuthorize("@ps.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public R optionselect() {
        return R.success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @Operation(summary = "查询已分配用户角色列表")
    @PreAuthorize("@ps.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    public R<PageResult<SysUser>> allocatedList(SysUser user, PageParam pageParam) {
        return R.success(userService.queryAllocatedPage(user,pageParam));
    }

    /**
     * 查询未分配用户角色列表
     */
    @Operation(summary = "查询未分配用户角色列表")
    @PreAuthorize("@ps.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    public R<PageResult<SysUser>>  unallocatedList(SysUser user, PageParam pageParam) {
        return R.success(userService.queryUnallocatedPage(user,pageParam));
    }

    /**
     * 取消授权用户
     */
    @Operation(summary = "取消授权用户")
    @PreAuthorize("@ps.hasPermi('system:role:edit')")
    @PutMapping("/authUser/cancel")
    public R cancelAuthUser(@RequestBody SysUserRole userRole) {
        return R.success(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @Operation(summary = "批量取消授权用户")
    @PreAuthorize("@ps.hasPermi('system:role:edit')")
    @PutMapping("/authUser/cancelAll")
    public R cancelAuthUserAll(Long roleId, Long[] userIds) {
        return R.success(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ps.hasPermi('system:role:edit')")
    @PutMapping("/authUser/selectAll")
    public R selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return R.success(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @Operation(summary = "获取对应角色部门树列表")
    @PreAuthorize("@ps.hasPermi('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public R deptTree(@PathVariable("roleId") Long roleId) {
        Map<String, Object> data = new HashMap<>();
        data.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        data.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return R.success(data);
    }
}
